package org.diy.redisson.entity;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;

import java.io.Serializable;

/**
 * @Author LHL
 * @Date 2020-10-27
 * @Description
 * @Version 1.0
 */
@Data
@Setter(AccessLevel.NONE)
public class Result<T> implements Serializable {

    public final static String SUCCESS_CODE="00000";
    public final static Result SUCCESS = Result.build(SUCCESS_CODE);

    public final static Result FRONTEND_ERR = Result.build(ErrorCode.A0001);
    public final static Result SYSTEM_ERR = Result.build(ErrorCode.B0001);
    public final static Result THIRD_PARTY_ERR = Result.build(ErrorCode.C0001);

    public static <T> Result<T> build(String code){
        return new Result<T>(code,null,null);
    }

    public static <T> Result<T> build(String code,String info){
        return new Result<T>(code,info,null);
    }

    public static <T> Result<T> build(String code,String info,T data){
        return new Result<T>(code,info,data);
    }

    public static <T> Result<T> build(String code,T data){
        return new Result<T>(code,null,data);
    }

    public static <T> Result<T> build(T data){
        return new Result<T>(data);
    }

    public static <T> Result<T> build(ErrorCode code){
        return new Result<T>(code.name(),code.getMsg());
    }

    public static <T> Result<T> build(ErrorCode code,String info){
        return new Result<T>(code.name(),info);
    }

    public static <T> Result<T> build(ErrorCode code,String info, T data){
        return new Result<T>(code.name(),info,data);
    }



    private final String code;

    private final String info;

    private final T data;


    public Result(T data) {
        this(SUCCESS_CODE,null,data);
    }

    public Result(String code) {
        this(code,null,null);
    }

    public Result(String code, String info) {
        this(code,info,null);
    }

    @JsonCreator
    public Result(@JsonProperty("code") String code, @JsonProperty("info") String info, @JsonProperty("data") T data) {
        super();
        this.code=code;
        this.info=info;
        this.data=data;
    }

    /**
     * 判断Result是否成功的快捷方法
     * @return
     */
    @JsonIgnore
    public boolean isSuccess(){
        return SUCCESS_CODE.equals(code);
    }

    @Override
    public String toString(){
        return String.format("{\"code\":%s,\"info\":%s,\"data\":%s}",code,info,data);
    }

}
